package com.atguigu.yygh.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.yygh.cmn.listener.DictListener;
import com.atguigu.yygh.cmn.mapper.DictMapper;
import com.atguigu.yygh.cmn.service.DictService;
import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.model.cmn.Dict;
import com.atguigu.yygh.vo.cmn.DictEeVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.bytebuddy.implementation.bytecode.Throw;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Service
public class DictServiceImpl   extends ServiceImpl<DictMapper , Dict> implements DictService {

    @Autowired
    private  DictMapper  dictMapper;



    @Override
    @Cacheable(value="dict",keyGenerator = "keyGenerator")
    public List<Dict> selectById(Long id) {


        QueryWrapper<Dict> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("parent_id",id);
        List<Dict> dicts = dictMapper.selectList(queryWrapper);
        for(Dict d:dicts){
               Long dictId =d.getId();
            boolean estimate = estimate(dictId);
               d.setHasChildren(estimate);
        }



        return dicts;
    }

    @Override
    public void expertDiceData(HttpServletResponse response) {
        //设置下载信息
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = "dict";
        response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");
        //查询数据库
        List<Dict> dictList = baseMapper.selectList(null);
        //Dict -- DictEeVo
        List<DictEeVo> dictVoList = new ArrayList<>();
        for(Dict dict:dictList) {
            DictEeVo dictEeVo = new DictEeVo();
            // dictEeVo.setId(dict.getId());
            BeanUtils.copyProperties(dict,dictEeVo);
            dictVoList.add(dictEeVo);
        }
        //调用方法进行写操作
        try {
            EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("dict")
                    .doWrite(dictVoList);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
//导入数据字典
    @Override
    @CacheEvict(value="dict",allEntries = true)
    public void importDictData(MultipartFile file) {

        try {
            EasyExcel.read(file.getInputStream(),DictEeVo.class,new DictListener(dictMapper)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    @Override
    @Cacheable(value="dict",keyGenerator = "keyGenerator")
    public List<Dict> findAll() {

        return dictMapper.selectList(null);
    }

    @Override
    public String getDictName(String dictCode, String value) {
        if (StringUtils.isEmpty(dictCode)) {
            QueryWrapper<Dict> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("value",value);
            Dict dict = dictMapper.selectOne(queryWrapper);
            String name = dict.getName();
            return name;
        }else{
            QueryWrapper<Dict> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("dict_code",dictCode);

            Dict dict = dictMapper.selectOne(queryWrapper);

            Long id = dict.getId();

             QueryWrapper<Dict > wrapper=new QueryWrapper<>();
               wrapper.eq("parent_id",id).eq("value",value);
            Dict dictTwo = dictMapper.selectOne(wrapper);

            return  dictTwo.getName();

        }


    }

    @Override
    public List<Dict> findByDictCode(String dictCode) {

       QueryWrapper<Dict> wrapper=new QueryWrapper<>();
         wrapper.eq("dict_code",dictCode);
        Dict dict = dictMapper.selectOne(wrapper);
        if(dict==null){

            throw new YyghException("值错误",201);

        }
        Long id = dict.getId();
       if(this.estimate(id)!=true){
           throw new YyghException("下面没有子节点",201);
       }
        QueryWrapper<Dict> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("parent_id",id);
        List<Dict> list = dictMapper.selectList(queryWrapper);

        return list;
    }

    //判断id下面是否有子节点
    public boolean  estimate(Long id){
         QueryWrapper<Dict> queryWrapper=new QueryWrapper<>();
         queryWrapper.eq("parent_id",id);

        Integer count = dictMapper.selectCount(queryWrapper);

    return  count>0;
    }
}
